<template>
	<view class="bizPage" :style="mainStore.themeColor">
		<status-bar :title="title" />
		<view class="tabs bgwhite" :style="{top: totalHeight + 'px'}">
			<up-tabs :list="tabList" :scrollable="false" :lineColor="mainStore.color" lineWidth="40" :activeStyle="{color:'#222',fontWeight:'bold'}"
				@click="tabClick"></up-tabs>
		</view>
		<view class="padding20" style="margin-top: 44px;">
			<view class="search bgwhite d-flex a-center m-bot20">
				<text class="iconfont icon-sousuo color-333 m-right20"></text>
				<input class="flex-1 size26" v-model="params" placeholder="搜索标题、正文" confirm-type="search" @blur="handleSearch" />
			</view>
			<block v-if="current == 0 && workList.length">
				<view class="card" @click="toUrl('/bizPage/task/workDetails?id=' + item.id)" v-for="(item,index) in workList" :key="index">
					<view class="item d-flex a-center" v-if="item.currentReviewerUserId == mainStore.userInfo.userId">
						<image :src="item.avatar ? imgUrls(item.avatar) : staticImg + 'noExist.jpg'" mode="aspectFill" class="avatar m-right14"></image>
						<view class="size24 color-666">{{ item.ename }} 提交的工作任务审批</view>
					</view>
					<view class="item">
						<view class="size28 color-222">工作任务：</view>
						<view class="flex-1 text-right size28 color-666">{{ item.taskName }}</view>
						<text class="iconfont icon-zhengque-fill size32" style="color: #12b7bd;" v-if="item.status == 1"></text>
						<text class="iconfont icon-cuowu-fill size32" style="color: #ff575f;" v-if="item.status == 2"></text>
					</view>
					<view class="item">
						<view class="size28 color-222">倒计时：</view>
						<view class="flex-1 text-right size28 color-666">{{ item.diffDay }}天</view>
					</view>
					<view class="item" v-if="item.fileUrl || (item.userId == mainStore.userInfo.userId && (item.status == 0 || item.status == 2))">
						<choose-file class="width" :rawFile="item.fileUrl" :current="index" :readonly="!(item.userId == mainStore.userInfo.userId && (item.status == 0 || item.status == 2))"
							@getFile="getFile" />
					</view>
					<!-- 提交后status从0变为4 -->
					<view class="item flexac" v-if="item.userId == mainStore.userInfo.userId && (item.status == 0 || item.status == 2)">
						<view class="btn flexac plain" @click.stop="handleTransfer(item)">转交</view>
						<view class="btn flexac themeBg white" @click.stop="handleSubmit(item)">提交</view>
					</view>
					<view class="item flexac" v-if="item.currentReviewerUserId == mainStore.userInfo.userId && state == 0">
						<view class="btn flexac fail" @click.stop="handleAudit(item, '0')">不通过</view>
						<view class="btn flexac themeBg white" @click.stop="handleAudit(item, '1')">通过</view>
					</view>
				</view>
			</block>
			<block v-if="current == 1 && list.length">
				<view class="task bgwhite m-bot20 color-222" @click="toUrl('/bizPage/task/details?processInstanceId=' + item.process.processInstanceId + '&state=' + state)" 
					v-for="(item,index) in list" :key="index">
					<view class="d-flex a-center m-bot34">
						<image class="avatar m-right20" :src="item.applyUserInfo?.avatar ? imgUrls(item.applyUserInfo.avatar) : staticImg + 'noExist.jpg'" mode="aspectFill"></image>
						<view class="flex-1 size28 bold m-right20">{{ item.applyUserInfo?.userName }}提交的{{ item.processDefinitionName }}</view>
						<view class="size26" style="color: #E95A30;" v-if="item.process && item.process.processStatus == 1">待处理</view>
						<view class="size26" style="color: #49C85B;" v-if="item.process && item.process.processStatus == 2">审批通过</view>
						<view class="size26" style="color: #F71C1C;" v-if="item.process && item.process.processStatus == 3">已驳回</view>
						<view class="size26 color-999" v-if="item.process && item.process.processStatus == 4">已取消</view>
						<view class="size26" style="color: #F71C1C;" v-if="item.process && item.process.processStatus == 5">已退回</view>
					</view>
					<view class="size26 m-bot20">发起申请时间：{{ item.process.startTime }}</view>
					<block v-if="item.formFieldInfos && item.formFieldInfos.length">
						<block v-for="(subItem,subIndex) in item.formFieldInfos" :key="subIndex">
							<view class="size26 ellipsis_1 m-bot20" v-if="subItem.fieldType != 'post' && subItem.fieldType != 'file'">
								{{ subItem.title }}：{{ subItem.value }}
							</view>
						</block>
					</block>
				</view>
			</block>
		</view>

		<up-empty :show="noData" mode="list" marginTop="100"></up-empty>

		<up-popup :show="showPopup" :round="10" closeable @close="showPopup = false">
			<view class="botPop">
				<block v-if="examine == 0">
					<view class="size32 bold text-center m-bot30">审核不通过</view>
					<up-textarea v-model="auditContent" placeholder="请输入审核不通过原因" height="154"></up-textarea>
				</block>
				<block v-if="examine == 1">
					<view class="size32 bold text-center m-bot70">评分：{{ score }}分</view>
					<view class="p-left40 p-right40">
						<view class="star" v-for="(item,index) in 10" :key="index">
							<image :src="staticImg + (score > index ? 'star-fill.png' : 'star.png')" mode="aspectFill" class="icon" @click="score = index + 1"></image>
						</view>
					</view>
				</block>
				<view class="btn flexac themeBg size30 white m-top60" @click="confirm">确认</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import { ref, computed } from 'vue'
	import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app'
	import { useMainStore } from '@/stores/index'
	import { staticImg } from '@/utils/config.js'
	import { toUrl, Toast, imgUrls, Modal } from '@/utils/utils.js'
	import Http from '@/utils/request.js'
	import statusBar from '../components/statusBar.vue'
	import chooseFile from '../components/chooseFile.vue'
	
	const mainStore = useMainStore()
	const totalHeight = computed(() => {
		return mainStore.statusBarHeight + mainStore.navBarHeight
	})
	const tabList = ref([
		{ name: '工作任务' },
		{ name: '流程任务' }
	])
	const current = ref(0)
	const tabClick = (item) => {
		current.value = item.index
		handleSearch()
	}
	
	const workList = ref([])
	const list = ref([])
	const page = ref(1)
	const limit = ref(10)
	const noData = ref(false)
	const noMore = ref(false)
	
	const state = ref('') // 0待办、1已办
	const title = ref('')
	const params = ref('')
	
	onLoad((e) => {
		if(e.state) state.value = e.state
		title.value = state.value == 0 ? '待办任务' : '已办任务'
	})

	onShow(() => {
		handleSearch()
		let userId = uni.getStorageSync('targetUserId')
		if(userId) {
			transferTask(userId)
			uni.removeStorageSync('targetUserId')
		}
	})

	const getWork = () => {
		noData.value = false
		noMore.value = false
		Http.get({
			url: '/hr/task/workTaskHandlingList',
			data: {
				is_over: state.value == 0 ? '1' : '0',
				params: params.value,
				pageNum: page.value,
				pageSize: limit.value
			}
		}).then(res => {
			if(res.code != 0) return Toast(res.msg)
			let result = res.rows || []
			workList.value = page.value == 1 ? result : workList.value.concat(result)
			if(!workList.value.length) noData.value = true
			if(result.length < limit.value) noMore.value = true
		})
	}
	
	const getList = () => {
		noData.value = false
		noMore.value = false
		let url = '/hr/process/my/todo' // 流程待办
		if(state.value == 1) url = '/hr/process/my/done' // 流程已办
		Http.post({
			url,
			data: {
				pageNum: page.value,
				pageSize: limit.value,
				params: params.value
			}
		}).then(res => {
			if(res.code != 0) return Toast(res.msg)
			let result = res.data.pagedRecords || []
			list.value = page.value == 1 ? result : list.value.concat(result)
			if(!list.value.length) noData.value = true
			if(result.length < limit.value) noMore.value = true
		})
	}
	
	const handleSearch = () => {
		page.value = 1
		if(current.value == 0) getWork()
		if(current.value == 1) getList()
	}
	
	onReachBottom(() => {
		if(noMore.value) return
		page.value ++
		if(current.value == 0) getWork()
		if(current.value == 1) getList()
	})

	// 提交
	const getFile = ({file, index}) => {
		workList.value[index].fileUrl = file
	}
	const handleSubmit = (item) => {
		Http.post({
			url: '/hr/task/submitTask',
			data: {
				taskId: item.id,
				fileUrl: item.fileUrl
			}
		}).then(res => {
			Toast(res.msg)
			if(res.code == 0) handleSearch()
		})
	}

	// 审核
	const showPopup = ref(false)
	const examine = ref('') // 0不通过、1通过
	const auditContent = ref('')
	const score = ref(1)
	const Obj = ref('')
	const handleAudit = async (item, val) => {
		Obj.value = item
		examine.value = val
		if(examine.value == 1 && item.scoreUserId != mainStore.userInfo.userId) {
			let result = await Modal('确定通过吗？')
			if(result) confirm()
			return 
		}
		showPopup.value = true
	}

	const confirm = () => {
		let params = {
			taskId: Obj.value.id,
			currentReviewerUserId: Obj.value.currentReviewerUserId,
			examine: examine.value
		}
		if(examine.value == 0) params.auditContent = auditContent.value
		if(examine.value == 1 && Obj.value.scoreUserId == mainStore.userInfo.userId) params.score = score.value
		Http.post({
			url: '/hr/task/taskreview',
			data: params
		}).then(res => {
			Toast(res.msg)
			if(res.code != 0) return
			handleSearch()
			showPopup.value = false
		})
	}

	// 转交
	const handleTransfer = (item) => {
		Obj.value = item
		toUrl('/bizPage/task/selectList?title=转交')
	}
	const transferTask = (userId) => {
		Http.post({
			url: '/hr/task/workTransferTask',
			data: {
				userId,
				taskId: Obj.value.id,
				fileUrl: Obj.value.fileUrl
			}
		}).then(res => {
			Toast(res.msg)
			if(res.code == 0) handleSearch()
		})
	}
</script>

<style lang="scss" scoped>
	.bizPage {
		min-height: 100vh;
		background: #F9F9F9;
	}
	.tabs {
		width: 100%;
		position: fixed;
		left: 0;
		z-index: 11;
	}
	.search {
		height: 66rpx;
		box-shadow: 0rpx 3rpx 4rpx 0rpx rgba(58,100,132,0.11);
		border-radius: 33rpx;
		padding: 0 20rpx;
	}
	.card {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 0 20rpx;
		margin-bottom: 20rpx;
		.item {
			padding: 30rpx 0;
			display: flex;
			&:not(:last-child) {
				border-bottom: 1rpx solid #F2F2F2;
			}
			.btn {
				width: 132rpx;
				height: 48rpx;
				border-radius: 7rpx;
				font-size: 26rpx;
				margin: 0 30rpx;
				&.plain {
					border: 1rpx solid v-bind('mainStore.color');
					color: v-bind('mainStore.color');
				}
				&.fail {
					border: 1rpx solid #E60012;
					color: #E60012;
				}
			}
		}
	}
	.task {
		border-radius: 20rpx;
		padding: 36rpx 26rpx 36rpx 30rpx;
	}
	.botPop {
		padding: 40rpx 30rpx;
		.btn {
			height: 96rpx;
			border-radius: 12rpx;
		}
	}
	.star {
		display: inline-block;
		width: 20%;
		text-align: center;
		margin-bottom: 26rpx;
		.icon {
			width: 76rpx;
			height: 74rpx;
		}
	}
	.avatar {
		width: 66rpx;
		height: 66rpx;
		border-radius: 10rpx;
	}
</style>
